package com.openarena.model.dao;

import com.openarena.model.Player;
import com.openarena.model.Game;
import com.openarena.model.GamePoint;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Query;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

public class GamePointsDAO extends InfArenaDAO {

    private static final Logger logger = Logger.getLogger(GamePointsDAO.class.getCanonicalName());

    public GamePointsDAO() {
    }

    public List<GamePoint> getGamePointsByGame(Game game) {
        Session session = null;
        try {
            session = getSession();
            return session.createCriteria(GamePoint.class).add(Restrictions.eq("gameId", game.getId())).list();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return Collections.EMPTY_LIST;
        } finally {
            close(session);
        }
    }

    public List<GamePoint> getGamePointsByGameAndPlayer(Game game, Player player) {
        Session session = null;
        try {
            session = getSession();
            return session.createCriteria(GamePoint.class).add(Restrictions.eq("gameId", game.getId())).add(Restrictions.eq("playerId", player.getId())).list();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return Collections.EMPTY_LIST;
        } finally {
            close(session);
        }
    }

    public Integer getMaxGamePointsByGameAndPlayer(Game game, Player player) {
        Session session = null;
        try {
            session = getSession();
            return (Integer) session.createCriteria(GamePoint.class).add(Restrictions.eq("gameId", game.getId())).add(Restrictions.eq("playerId", player.getId())).setProjection(Projections.max("points")).uniqueResult();

        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return null;
        } finally {
            close(session);
        }
    }

    public List<GamePoint> getMaxGamePointsByGame(Game game) {
        Session session = null;
        try {
            session = getSession();
            Query query = session.createQuery("from GamePoints gp where gp.gameId = :gameId"
                    + " and gp.points = (select max(gp2.points) from GamePoints gp2 where gp2.gameId = :gameId)");
            query.setInteger("gameId", Integer.valueOf(game.getId()));
            return query.list();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
            return Collections.EMPTY_LIST;
        } finally {
            close(session);
        }
    }
}
